#!/bin/sh

set -e

# chech privileged
checkPrivileged() {
  if ls /dev/*network* >/dev/null; then
    echo "Container start"
  else
    container_id=$(grep docker /proc/self/cgroup | sort -n | head -n 1 | cut -d: -f3 | cut -d/ -f3)
    echo "Container cannot start ID:$container_id"
    echo "Please ensure 'docker run' option '--privileged'."
    exit 1
  fi
}

checkPrivileged

# set env
N2N_LOCALHOST="localhost"
N2N_MAINPORT=7654
N2N_MANAGEMENTPORT=5645
N2N_NETWORK="edge0"
N2N_GROUP="N2NNetwork"
N2N_KEY="85f7a0affa50d933485a215eb10fb921"

DHCPD_SUBNET="10.110.120.0"
DHCPD_NETMASK="255.255.255.0"

DHCPD_RANGE_S="10.110.120.2"
DHCPD_RANGE_D="10.110.120.254"

DHCPD_ROUTERS="10.110.120.1"
DHCPD_BROADCAST="10.110.120.255"

EDGE_IP=$DHCPD_ROUTERS

# set conf
echo """
INTERFACESv4=\"$N2N_NETWORK\"
INTERFACESv6=\"\"
""" >/etc/default/isc-dhcp-server

echo """
# A slightly different configuration for an internal subnet.
subnet $DHCPD_SUBNET netmask $DHCPD_NETMASK {
  range $DHCPD_RANGE_S $DHCPD_RANGE_D;
  # option domain-name-servers ns1.internal.example.org;
  # option domain-name \"internal.example.org\";
  option subnet-mask $DHCPD_NETMASK;
  option routers $DHCPD_ROUTERS;
  option broadcast-address $DHCPD_BROADCAST;
  default-lease-time 604800;
  max-lease-time 1209600;
}
""" >/etc/dhcp/dhcpd.conf

echo """
-l=$N2N_MAINPORT
-v
-f
""" >/tmp/supernode.conf

echo """
-d=$N2N_NETWORK
-a=$EDGE_IP
-c=$N2N_GROUP
-k=$N2N_KEY
-l=$N2N_LOCALHOST:$N2N_MAINPORT
-v
""" >/tmp/edge.conf

# start
/usr/bin/supernode /tmp/supernode.conf >/tmp/supernode.log 2>&1 &
/usr/bin/edge /tmp/edge.conf >/tmp/edge.log 2>&1 &
echo "isc-dhcp-server restart"
service isc-dhcp-server restart
tail -f /tmp/supernode.log
